package cn.easybuy.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class FileUtil {
    public static void fileUpload(HttpServletRequest req, Map<String, String> map) throws Exception {
        boolean b = ServletFileUpload.isMultipartContent(req);
        String path = req.getServletContext().getRealPath("/files/");
        //easy_buy/web/files
//        String path ="web/files";
        if (b) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem fileItem : list) {
                if (!fileItem.isFormField()) {
                    String name = fileItem.getName();
                    if (!"".equals(name.trim()) && name != null) {
                        map.put("filename", name);
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String str = UUID.randomUUID().toString();
                        int index = name.lastIndexOf(".");
                        String suff = name.substring(index);
                        String newName = str + suff;
                        File file2 = new File(file, newName);
                        map.put("filepath", file2.getPath());
                        map.put("newName",newName);
                        if (!file2.exists()) {
                            file2.createNewFile();
                        }
                        fileItem.write(file2);
                    }
                } else {
                    String value = fileItem.getString("utf-8");
                    String name = fileItem.getFieldName();
                    map.put(name, value);
                }
            }
        }
    }

}
